﻿using ETWJ.DTO;
using ETWJ.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ETWJ.Service
{
    public abstract class CommonService<TEntity, TDTO, TDbCtx>   
       //约束
       where TEntity : BaseModel    
       where TDTO : BaseDTO
       where TDbCtx : MyDbContext, new()
    {
        public virtual async Task<int> AddNewAsync(TEntity dto)
        {
            TEntity en = AutoMapper.Mapper.Map<TEntity>(dto);
            using (TDbCtx ctx = new TDbCtx())
            {
                await ctx.Set<TEntity>().AddAsync(en);
                return await ctx.SaveChangesAsync();
            }
        }

        public virtual async Task<TDTO> GetByIdAsync(int id)
        {
            using (TDbCtx ctx = new TDbCtx())
            {
                BaseService<TEntity> bs = new BaseService<TEntity>(ctx);
                var en = await bs.GetAll()
                    .AsNoTracking()
                    .SingleOrDefaultAsync(e => e.Id == id);
                return en == null ? null : AutoMapper.Mapper.Map<TDTO>(en);
            }
        }

        public virtual async Task<List<TDTO>> GetALL()
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                List<TDTO> list = new List<TDTO>();
                BaseService<TEntity> bs = new BaseService<TEntity>(ctx);
                await bs.GetAll().AsNoTracking().ForEachAsync(e =>
                {
                    list.Add(AutoMapper.Mapper.Map<TDTO>(e));
                });
                return list;
            }
        }

        public virtual async Task<List<TDTO>> GetByPage(int Pageindex = 1, int count = 10)
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                List<TDTO> list = new List<TDTO>();
                BaseService<TEntity> bs = new BaseService<TEntity>(ctx);
                await bs.GetByPage(Pageindex, count).AsNoTracking().ForEachAsync(e => {
                    list.Add(AutoMapper.Mapper.Map<TDTO>(e));
                });
                return list;
            }
        }

        public virtual async Task<int> GetTotalCountAsync()
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                BaseService<TEntity> bs = new BaseService<TEntity>(ctx);
                return await bs.GetCount();

            }
        }

        public virtual async Task<int> MarkDeleted(int id)
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                BaseService<TEntity> bs = new BaseService<TEntity>(ctx);
                return await bs.MarkDeleted(id);
            }
        }

    }
}
